﻿using System;
using System.Web;
using System.Collections.Generic;
using Util;

    /// <summary>
    /// Ajax调用ashx页面的基础类
    /// 继承BaseHandler,将 ProcessRequest(HttpContext context) 方法进行了密封
    /// 含处理流程,验证,方法映射
    /// </summary>
public abstract class BaseAjaxHandler : BaseHandler
{
    #region 常量声明
    /// <summary>
    /// 标识操作的参数名
    /// </summary>
    protected static string OPERATION_ID = "op";

    #endregion

    #region 成员变量

    private IDictionary<string, string> _oprationMap = new Dictionary<string, string>();
    /// <summary>
    /// 操作图,op参数的值根据此图来寻找方法，从而动态调用
    /// key为op参数的值,value为将调用的方法名
    /// </summary>
    public IDictionary<string, string> OprationMap
    {
        get { return _oprationMap; }

    }

    private string _op;
    /// <summary>
    /// 操作标识
    /// </summary>
    public string Op
    {
        get { return _op; }
        set { _op = value; }
    }


    // 执行是否成功,默认false
    private bool _isSuccess = false;
    /// <summary>
    /// 标识是否全部执行成功
    /// </summary>
    public bool IsSuccess
    {
        get { return _isSuccess; }
        set { _isSuccess = value; }
    }


    private string _message = Constants.INFO_UNKNOWN_ERR;
    /// <summary>
    /// 返回给调用者的信息
    /// </summary>
    public string Message
    {
        get { return _message; }
        set { _message = value; }
    }


    private string _responseText;
    /// <summary>
    /// 要返回给Ajax调用者的值，若执行成功返回，必须将IsSuccess设置为True
    /// </summary>
    public string ResponseText
    {
        get { return this._responseText; }
        set { this._responseText = value; }
    }
    #endregion

    #region RequestProcess调用流程
    /// <summary>
    /// 初始化
    /// </summary>
    private void Init()
    {

        // 初始化操作表
        //OprationMap["add"] = "Add";
        //OprationMap["delete"] = "Delete";
        //OprationMap["update"] = "Update";
        //OprationMap["list"] = "List";

        // 设置返回格式
        //Context.Response.ContentType = "text/plain";

        // 设置操作标识
        Op = Context.Request[OPERATION_ID] as string;

        // 获得当前用户
        CurrentUser = Context.Session[Constants.SESS_USER_KEY] as SessionUser;
    }


    /// <summary>
    /// 方法映射
    /// </summary>
    protected virtual void Mapping()
    {

    }

    /// <summary>
    /// 返回JSON数据通用模板，数据集合中根结点默认为data
    /// </summary>
    /// <param name="flag"></param>
    /// <param name="?"></param>
    protected void WriteTemplateResponse(bool flag, string data)
    {
        IsSuccess = flag;

        if (flag)
        {
            ResponseText = "{" + string.Format(@"""success"":true,""data"":{0}", data) + "}";
        }
        else
        {
            ResponseText = "{" + string.Format(@"""success"":false,""msg"":{0}", data) + "}";
        }
    }

    /// <summary>
    /// 打印结果
    /// </summary>
    protected virtual void Response()
    {
        //---- 打印返回的数据 若整个请求不成功，则返回错误信息
        if (!IsSuccess)
        {
            ResponseText = "{success:false, msg:'" + Message.Replace("'", "") + "'}";
        }

        Context.Response.Write(ResponseText);
    }
    #endregion


    #region IHttpHandler接口实现
    /// <summary>
    /// 定义处理流程,不允许被重写
    /// </summary>
    /// <param name="context">当前上下文</param>
    public sealed override void ProcessRequest(HttpContext context)
    {
        base.ProcessRequest(context);

        // 初始化
        Init();

        // 映射方法
        Mapping();

        // ----调用相应处理方法
        if (Op != null)
        {
            try
            {
                InvokeHelper.ExecuteMethod(this, OprationMap[Op] as string);
            }
            catch (Exception e)
            {
                Message = e.Message;   // 返回信息
            }
        }
        // -----

        // 响应调用者,打印结果
        Response();
    }

    #endregion
}